package com.hpin.mlxteacher.ui;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.hpin.mlxteacher.R;
import com.hpin.mlxteacher.base.BaseActivity;
import com.hpin.mlxteacher.bean.LoginResult;
import com.hpin.mlxteacher.utils.CommonUtils;
import com.hpin.mlxteacher.utils.Constant;
import com.hpin.mlxteacher.utils.HttpUtil;
import com.hpin.mlxteacher.utils.LogUtil;

import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

//import com.umeng.analytics.MobclickAgent;

/**
 * 登录
 * Created by Administrator on 2015/7/14.
 */
public class LoginActivity extends BaseActivity {

    private TextView tv_forget_psw;
    private ImageView iv_delete_psw;
    private EditText et_username;
    private EditText et_psw;
    private TextView tv_login;
    private TextView tv_register;
    private Intent mIntent;
    private ImageView iv_delete_username;
    //是否需要自动登录
    private boolean isAutoLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);

//        //透明状态栏
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//        //透明导航栏
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        isAutoLogin = getIntent().getBooleanExtra("isAutoLogin", true);

        mApplication.addActivity(this);

        initWidget();
    }

    public void initWidget() {

        et_psw = (EditText) findViewById(R.id.et_psw);
        et_username = (EditText) findViewById(R.id.et_username);
        iv_delete_psw = (ImageView) findViewById(R.id.iv_delete_psw);
        tv_forget_psw = (TextView) findViewById(R.id.tv_forget_psw);
        tv_login = (TextView) findViewById(R.id.tv_login);
        tv_register = (TextView) findViewById(R.id.tv_register);

        iv_delete_username = (ImageView) findViewById(R.id.iv_delete_username);

        iv_delete_psw.setOnClickListener(this);
        tv_forget_psw.setOnClickListener(this);
        tv_login.setOnClickListener(this);
        iv_delete_username.setOnClickListener(this);
        tv_register.setOnClickListener(this);

        et_username.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    //显示叉号
                    iv_delete_username.setVisibility(et_username.getText().toString().trim().length() > 0 ? View.VISIBLE : View.INVISIBLE);

                    et_username.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                        }

                        @Override
                        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                            //显示叉号
                            iv_delete_username.setVisibility(et_username.getText().toString().trim().length() > 0 ? View.VISIBLE : View.INVISIBLE);

                        }

                        @Override
                        public void afterTextChanged(Editable editable) {
                        }
                    });

                } else {
                    iv_delete_username.setVisibility(View.INVISIBLE);

                }
            }
        });

        et_psw.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    //显示叉号
                    iv_delete_psw.setVisibility(et_psw.getText().toString().trim().length() > 0 ? View.VISIBLE : View.INVISIBLE);
                    et_psw.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                        }

                        @Override
                        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                            //显示叉号
                            iv_delete_psw.setVisibility(et_psw.getText().toString().trim().length() > 0 ? View.VISIBLE : View.INVISIBLE);
                        }

                        @Override
                        public void afterTextChanged(Editable editable) {

                        }
                    });

                } else {
                    iv_delete_psw.setVisibility(View.INVISIBLE);
                }
            }
        });

        //自动登录
        autoLogin();

    }

    /**
     * 自动登录
     */
    private void autoLogin() {

        String userName = sp.getString(Constant.USERNAME, "");
        String psw = sp.getString(Constant.PSW, "");

        if (CommonUtils.isNull(userName) || CommonUtils.isNull(psw))
            return;
        et_username.setText(userName);
        et_psw.setText(psw);

        et_username.setSelection(userName.length());
        et_psw.setSelection(psw.length());

        //是否自动登录
        if (isAutoLogin)
            login(userName, psw);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        et_username.setText(sp.getString(Constant.USERNAME, ""));
        if (!CommonUtils.isNull(et_username.getText().toString().trim()))
            et_username.setSelection(et_username.getText().toString().trim().length());
        et_psw.setText("");

    }


    private void showSoftInput(EditText editText) {

        InputMethodManager inputManager =
                (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(editText, 0);

    }


    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {

            case R.id.iv_delete_psw:
                //刪除密碼

                et_psw.setText("");

                showSoftInput(et_psw);

                break;
            case R.id.iv_delete_username:
                //刪除用户名

                et_username.setText("");
                showSoftInput(et_username);

                break;

            case R.id.tv_forget_psw:
                //忘記密碼

                mIntent = new Intent(this, ForgetPswActivity.class);
                startActivity(mIntent);

                break;

            case R.id.tv_login:  //登錄

                if (CommonUtils.isNull(et_username.getText().toString().trim())) {
                    showToast("请输入用户名");
                    return;
                }

                if (!CommonUtils.isPhone(et_username.getText().toString().trim())) {
                    showToast("请输入正确的手机号码");
                    return;
                }

                if (CommonUtils.isNull(et_psw.getText().toString().trim())) {
                    showToast("请输入密码");
                    return;
                }

                String unEncryptpsw = et_psw.getText().toString().trim();
                //密码MD5加密
                String md5Psw = "";

                if (Constant.MINGLUXING_CODE.equals(unEncryptpsw)) {
                    //记住密码时 点击的登录
                    md5Psw = sp.getString(Constant.PSW, "");
                } else {
                    md5Psw = CommonUtils.toMd5(unEncryptpsw.getBytes());
                }

                //登錄
                login(et_username.getText().toString().trim(), md5Psw);
                break;

            case R.id.tv_register:
                //注册

                mIntent = new Intent(this, RegisterActivity.class);
                startActivity(mIntent);

                break;
        }

    }

    /**
     * 登陆
     */
    private void login(final String userName, final String psw) {

        JSONObject j = new JSONObject();
        j.put("phoneNum", userName);
        j.put("pwd", psw);

        HttpUtil.setPostRequest("登录中...", this, Constant.WEB_ROOT + Constant.LOGIN,
                j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {

                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            LoginResult loginResult = JSONObject.parseObject(str, LoginResult.class);

                            if (loginResult == null) {
                                showToast("登陆失败");
                                return;
                            }

                            if (loginResult.code == Constant.SUCCESS) {//成功

                                if (loginResult.data == null && loginResult.token == null) {
                                    showToast("登陆失败");
                                    return;
                                }

                                //防止意外退出时 切换账号后 sp中文件未清理完全
                                if (!TextUtils.isEmpty(sp.getString(Constant.phoneNum, "")) && !userName.equals(sp.getString(Constant.phoneNum, ""))) {
                                    sp.edit().clear().apply();
                                }

                                //极光推送 设置推送的别名
                                if (loginResult.data.mobile != null)
                                    setAlias(loginResult.data.mobile);

                                //保存用户的数据
                                SharedPreferences.Editor editor = sp.edit();
                                editor.putString(Constant.phoneNum, loginResult.data.mobile);
                                editor.putString(Constant.nickName, loginResult.data.nickName);
                                editor.putString(Constant.imgUrl, loginResult.data.userImg);
                                editor.putString(Constant.sex, loginResult.data.sex);
                                editor.putString(Constant.birthday, loginResult.data.birthDay);
//                        editor.putString(Constant.classGrade, loginResult.data.classGrade);
                                editor.putString(Constant.id, loginResult.data.id);
                                editor.putString(Constant.token, loginResult.token.token);

                                //保存用户名和密码 下次自动登录用
                                editor.putString(Constant.USERNAME, userName);
                                editor.putString(Constant.PSW, psw);

                                Object readObj = CommonUtils.readObj(Constant.REMAIND + userName);

                                if (readObj != null) {

                                    Set<String> remaind = (Set<String>) readObj;
                                    editor.putStringSet(Constant.REMAIND + userName, remaind).apply();

                                } else {
                                    Log.e("tag", " readObj 为 空 ");
                                }

                                editor.apply();

                                Intent mIntent = new Intent(LoginActivity.this, HomeActivity.class);
                                startActivity(mIntent);
//                        finish();

                            } else {
                                //弹出错误提示
                                showToast(Constant.showErrorMsg(loginResult.code, LoginActivity.this));
                            }

                        } catch (Exception e) {
                            LogUtil.e("TAG", "json 解析错误==>>>" + str);
                            e.printStackTrace();
                        }

                    }

                }, null);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        mApplication.cancelPendingRequests(getClass().getName());

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        mApplication.exit();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {

            // 获得当前得到焦点的View，一般情况下就是EditText（特殊情况就是轨迹求或者实体案件会移动焦点）
            View v = getCurrentFocus();

            if (isShouldHideInput(v, ev)) {
                hideSoftInput(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时没必要隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left
                    + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditView上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 多种隐藏软件盘方法的其中一种
     *
     * @param token
     */
    private void hideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token,
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    // 这是来自 JPush Example 的设置别名的 Activity 里的代码。一般 App 的设置的调用入口，在任何方便的地方调用都可以。
    private void setAlias(String userId) {

        LogUtil.e("tag", "别名:" + userId);

        if (CommonUtils.isNull(userId)) {
            return;
        }

        // 调用 Handler 来异步设置别名
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, userId));
    }

    private static final int MSG_SET_ALIAS = 1001;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    LogUtil.e("TAG", "Set alias in handler.");
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
                    break;
                default:
                    LogUtil.e("TAG", "Unhandled msg - " + msg.what);
            }
        }
    };

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
//                    logs = "Set tag and alias success";
//                    LogUtil.e("TAG", logs);
                    LogUtil.e("tag", "设置别名成功");

                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    LogUtil.e("TAG", logs);
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    LogUtil.e("TAG", logs);
            }

        }
    };

//    public void onResume() {
//        super.onResume();
//        MobclickAgent.onPageStart(getClass().getName());
//        MobclickAgent.onResume(this);       //统计时长
//    }
//
//    public void onPause() {
//        super.onPause();
//        MobclickAgent.onPageEnd(getClass().getName());
//        MobclickAgent.onPause(this);
//    }

}
